package com.youxin.chat.pay.service.manager;

import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CacheRefresh;
import com.alicp.jetcache.anno.Cached;
import com.youxin.base.BaseResultCode;
import com.youxin.chat.pay.constant.PayRedisKey;
import com.youxin.chat.pay.mapper.UserWalletMapper;
import com.youxin.chat.pay.model.UserWallet;
import com.youxin.exception.SystemException;
import com.youxin.utils.MD5Util;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * description: UserWalletManager <br>
 * date: 2020/3/1 12:29 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class UserWalletManager {

    @Resource
    private UserWalletMapper userWalletMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public boolean validatePass(String userNo, String payPass, String realPass) {
        String salt = getSalt(userNo);
        String payPwd = MD5Util.md5Salt(payPass.toUpperCase(), salt, 1);

        return payPwd.equals(realPass);
    }

    @Cached(name = "pay.user.status.", key = "#userNo", expire = 1, timeUnit = TimeUnit.DAYS)
    @CacheRefresh(refresh = 1, timeUnit = TimeUnit.HOURS)
    public int getWalletStatus(String userNo) {
        Integer status = userWalletMapper.selectWalletStatus(userNo);
        return status;
    }

    @CacheInvalidate(name = "pay.user.status.", key = "#userNo")
    public void updateWalletStatus(String userNo, Integer status) {
        userWalletMapper.updateWalletStatus(userNo, status);

    }

    @Cached(name = "pay.user.password.", key = "#userNo", expire = 1, timeUnit = TimeUnit.DAYS)
    @CacheRefresh(refresh = 1, timeUnit = TimeUnit.HOURS)
    public String getPayPwd(String userNo) {
        UserWallet userWallet = userWalletMapper.selectUserWalleByUserNo(userNo);
        if (userWallet != null) {
            return userWallet.getPayPwd();
        } else {
            return "";
        }
    }

    @CacheInvalidate(name = "pay.user.password.", key = "#userNo")
    public void updateWalletPass(String userNo, String pass) {
        userWalletMapper.updateWalletPass(userNo, pass);

    }

    private String getSalt(String userNo) {
        int endIndex = userNo.length();
        int beginIndex = 0;

        if (endIndex > 6) {
            beginIndex = endIndex - 6;
        }
        String salt = userNo.substring(beginIndex, endIndex);
        return salt;
    }
}
